<?php
class ComponentStoreComponent extends Object{
	var $components = array( 'Auth','Session','RequestHandler');	

	function initialize(&$controller, $settings = array()) {
        // saving the controller reference for later use
        $this->controller =& $controller;
    }
    
    //called after Controller::beforeFilter()
    function startup(&$controller) {
    }
    
	public function get_products($group_id,$params){
		$model =& $this->getModel('StoreProduct');
	    if(!$model){
	      return false;
	    }
	    $product_schema = $model->schema();
	    $fields = array('StoreUpload.name','StoreCurrency.exchange','StoreCurrencyDefault.exchange','StoreCurrencyDefault.id');
		    if(is_array($product_schema)){
	    	foreach ($product_schema as $column => $value) {
	    		array_push($fields,"StoreProduct.{$column}");
	    	}
	    }else{
	    	$fields = array('StoreProduct.id','StoreProduct.name','StoreProduct.www','StoreUpload.name');
	    }
	    $model->recursive = -1;
	    $conditions = array();
	    $order = array();
	    $joins = array( array('table' => 'store_uploads', 'alias' => 'StoreUpload', 'type' => 'INNER', 'conditions' => array( 'StoreUpload.id = StoreProduct.upload_id')));
	     
	    if($group_id  == 'moust_viewed'){
	    	$order = array('StoreProduct.viewed' => 'DESC');
	    }else{
	    	$order = array('StoreProduct.lp_group');
	    	if(!is_null($group_id)) $conditions = array('StoreProduct.group_id'=>$group_id);
	    }

	    if(isset($params['conditions']) && is_array($params['conditions'])){
	    	foreach ($params['conditions'] as $cond_id => $value) {
	    		if($cond_id == 'model_id'){
	    			array_push($joins, array('table' => 'store_product_models', 'alias' => 'StoreProductModel', 'type' => 'INNER', 'conditions' => array( 'StoreProductModel.product_id = StoreProduct.id')));
					array_push($joins, array('table' => 'store_models', 'alias' => 'StoreModel', 'type' => 'INNER', 'conditions' => array( 'StoreProductModel.model_id = StoreModel.id')));
					$conditions['StoreModel.id'] = $value;
	    		}else{
	    			$conditions[$cond_id] = $value; 
	    		}
	    	}
	    	
	    }	    
	   
	    array_push($joins, array('table' => 'store_currencies', 'alias' => 'StoreCurrency', 'type' => 'INNER', 'conditions' => array( 'StoreCurrency.id = StoreProduct.currency_id')));
	    array_push($joins, array('table' => 'store_currencies', 'alias' => 'StoreCurrencyDefault', 'type' => 'INNER', 'conditions' => array( 'StoreCurrencyDefault.default = 1')));
	    $items = $model->find('all',array('fields'=>$fields,'joins'=>$joins,'conditions'=>$conditions,'order'=>$order,'limit'=>$params['limit']));
	    return $items;	    
	}
	
	function get_models(){
		$model =& $this->getModel('StoreModel');
	    if(!$model){
	      return false;
	    }	
	    return $model->find('list', array('order' => array('lp')));	
	}
	
	function get_categories($type = null) {
		$model =& $this->getModel('StoreCategory');
	    if(!$model){
	      return false;
	    }		
	    
	    switch($type){
	    	case 'main':
	    		$categories = $model->find('all', array('conditions'=>array('parent_id'=>'0'),'order' => array('lft')));
	    		break;
	    	case 'all':
	    		$categories = $model->find('all', array('order' => array('lft')));
	    		break;
	    	case 'selectbox':
	    		$categories = $categories = $model->find('all', array('conditions'=>array('parent_id'=>'0'),'order' => array('lft')));
	    		$parentCategories = $this->treeForCombobox($categories,'StoreCategory');
				return $parentCategories;
	    		break;
	    	default:
	    		$categories = $model->find('threaded', array('order' => array('lft')));
	    	
	    }				
		return $categories;
	}	
	
	function selectbox_categories(){
		$model =& $this->getModel('StoreCategory');
	    if(!$model){
	      return false;
	    }
		$parentCategory = $model->find('threaded', array());
		
	}
	
	function add(){
		
	}
	
	function &getModel($name = null) {
		$model = null;
		if (!$name) {
			$name = 'StoreProduct';
		}    
		if($name){
			if (PHP5) {
				$model = ClassRegistry::init($name);
			} else {
				$model =& ClassRegistry::init($name);
			}

			if (empty($model)) {
//				$this->_error('FileUpload::getModel() - Model is not set or could not be found');
				return null;
			}
		}
		return $model;
	}
	
	/**
	 * 
	 * Przekształcenie struktury Tree do wyświetlaneia w combobox lub na liscie
	 * @param array $data // dane z zapytania $model->find('treahend');
	 * @param string $model // nazwa modeluz którego pobrano dane
	 * @param bool $full // true: zwraca array dodając jedynie wartosc depth; false: zwaraca listę id => name; 
	 */
	protected function treeForCombobox($data,$model,$full=false){
		$parentCategories_ = $this->treeComboBox($data,$model);
		if($full) return $parentCategories_;
		$parentCategories = array();
        foreach ($parentCategories_ as $key => $value) {
        	$parentCategories[$value[$model]['id']] = $value[$model]['name'];
        }
        return $parentCategories;
	}
	

	/**
	 * 
	 * Dodaje wartość depth
	 * @param $data
	 * @param $model
	 */
	private function treeComboBox($data,$model) {

        $result = array();
        
		$modelObj =& $this->getModel($model);
	    if(!$modelObj){
	      return $result;
	    }
	    
        foreach ($data as $i) {
            $newData = $i;
            $newData[$model]['depth'] = count($modelObj->getpath($i[$model]['id'])) - 1;
            $newData[$model]['name'] = str_repeat(" . . . . . . . ", $newData[$model]['depth']).$newData[$model]['name'];
            
            unset($newData['children']);
            $result[] = $newData;
            if(isset($i['children']) && is_array($i['children'])) {
                $children = $this->treeComboBox($i['children'],$model);
                foreach($children as $k) {
                    $result[] = $k;
                }
            }
        }
        return $result;
    }
}